package api_day11;

public class SynTest {
    public static void main(String[] args) {
        //匿名内部类实现Runnable接口
        Runnable ticket = new Runnable() {
            private int ticket = 100;
            @Override
            public void run() {
                Thread t = Thread.currentThread();
                String name = t.getName();
                //开始不带锁，会出现卖同一张票以及卖不存在票的问题 - 线程冲突
                //利用synchronized修饰代码块来解决冲突
                while (true) {
                    //解决方式一 - 同步代码块
                    /*synchronized (this){
                        if (ticket > 0){
                            try {
                                t.sleep(333);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            System.out.println(name + "正在卖票，当前售卖票号为：" + ticket);
                            ticket--;
                        }else break;
                    }*/
                    //解决方式二 - 使用同步方法
                    sell();
                    if (ticket == 0) break;
                }
            }
            public synchronized void sell(){
                Thread t = Thread.currentThread();
                String name = t.getName();
                if (ticket > 0){
                    try {
                        t.sleep(50);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(name + "正在卖票，当前售卖票号为：" + ticket);
                    ticket--;
                }
            }
        };
        //静态同步方法测试对象
        Ticket t = new Ticket();
        //创建多个窗口
        Thread t1 = new Thread(t, "窗口1");
        Thread t2 = new Thread(t, "窗口2");
        Thread t3 = new Thread(t, "窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}